<template>
  <div class="player"
       v-show="playlist.length>0">
    <transition name="normal"
                @enter="enter"
                @after-enter="afterEnter"
                @leave="leave"
                @after-leave="afterLeave">
      <div class="normal-player"
           v-show="fullScreen">
        <div class="background">
          <img width="100%"
               height="100%"
               :src="currentSong.image"
               alt />
        </div>
        <div class="top">
          <div class="back"
               @click="back()">
            <i class="icon-back"></i>
          </div>
          <h1 class="title"
              v-html="currentSong.name"></h1>
          <h2 class="subtitle"
              v-html="currentSong.singer"></h2>
        </div>
        <div class="middle"
             @touchstart="middleTouchStart"
             @touchmove="middleTouchMove"
             @touchend="middleTouchEnd">
          <div class="middle-l"
               ref="middleL">
            <div class="cd-wrapper"
                 ref="cdWrapper">
              <div class="cd"
                   :class="cdCls">
                <img :src="currentSong.image"
                     alt
                     class="image" />
              </div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{playingLyric}}</div>
            </div>
          </div>
          <scroll class="middle-r"
                  ref="lyricList"
                  :data="currentLyric && currentLyric.lines">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p class="text"
                   :class="{'current':currentLineNum===index}"
                   ref="lyricLine"
                   v-for="(line,index) in currentLyric.lines"
                   :key="line+index">{{line.txt}}</p>
              </div>
            </div>
          </scroll>
        </div>
        <div class="bottom">
          <div class="dot-wrapper">
            <span class="dot"
                  :class="{'active':currentShow==='cd'}"></span>
            <span class="dot"
                  :class="{'active':currentShow==='lyric'}"></span>
          </div>
          <div class="progress-wrapper">
            <span class="time time-l">{{currentTime | timeFormat}}</span>
            <div class="progress-bar-wrapper">
              <progress-bar :percent="percent"
                            @percentChange="onProgressBarChange"></progress-bar>
            </div>
            <span class="time time-r">{{currentSong.duration | timeFormat}}</span>
          </div>
          <div class="operators">
            <div class="icon i-left">
              <i :class="iconMode"
                 @click="changeMode"></i>
            </div>
            <div class="icon i-left"
                 :class="disabled">
              <i class="icon-prev"
                 @click="prev"></i>
            </div>
            <div class="icon i-center"
                 :class="disabled">
              <i :class="playIcon"
                 @click="togglePlaying"></i>
            </div>
            <div class="icon i-right"
                 :class="disabled">
              <i class="icon-next"
                 @click="next"></i>
            </div>
            <div class="icon i-right">
              <i class="icon" @click="toggleFavorite(currentSong)" :class="getFavoriteIcon(currentSong)"></i>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <transition name="mini">
      <div class="mini-player"
           @click="open"
           v-show="!fullScreen">
        <div class="icon">
          <img width="40"
               height="40"
               :src="currentSong.image"
               alt />
        </div>
        <div class="text">
          <h2 class="name"
              v-html="currentSong.name"></h2>
          <p class="desc"
             v-html="currentSong.singer"></p>
        </div>
        <div class="control">
          <progress-circle :radius="radius"
                           :percent="percent">
            <i class="icon-mini"
               :class="miniPlayIcon"
               @click.stop="togglePlaying"></i>
          </progress-circle>
        </div>
        <div class="control"
             @click.stop="showPlaylist">
          <i class="icon-playlist"></i>
        </div>
      </div>
    </transition>
    <playlist ref="playlist"></playlist>
    <audio :src="songUrl"
           ref="audio"
           @error="error"
           @timeupdate="updateTime"
           @play="audioPlay"
           @pause="audioPause"
           @ended="ended"></audio>
  </div>
</template>

<script>
import { mapGetters, mapMutations, mapActions } from 'vuex'
import animations from 'create-keyframe-animation'
import { prefixStyle } from 'common/js/dom'
import { getSongUrl } from 'api/song'
import ProgressBar from 'base/progress-bar/progress-bar'
import ProgressCircle from 'base/progress-circle/progress-circle'
import { playMode } from 'common/js/config'
import Lyric from 'lyric-parser'
import Toast from 'base/toast'
import Scroll from 'base/scroll/scroll'
import { playerMixin } from 'common/js/mixin'
import Playlist from 'components/playlist/playlist'

const transform = prefixStyle('transform')
const transitionDuration = prefixStyle('transitionDuration')

export default {
  name: 'player',
  data () {
    return {
      songUrl: '',
      playerReady: false,
      currentTime: 0,
      radius: 32,
      currentLyric: null,
      currentLineNum: 0,
      currentShow: 'cd',
      playingLyric: '',
      createdTime: 0
    }
  },
  computed: {
    ...mapGetters([
      'fullScreen',
      'playlist',
      'currentSong',
      'playing',
      'currentIndex',
      'mode',
      'sequenceList'
    ]),
    playIcon () {
      return this.playing ? 'icon-pause' : 'icon-play'
    },
    miniPlayIcon () {
      return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
    },
    cdCls () {
      return this.playing ? 'play' : 'play pause'
    },
    disabled () {
      return this.playerReady ? '' : 'disable'
    },
    percent () {
      return this.currentTime / this.currentSong.duration
    },
    iconMode () {
      return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random'
    }
  },
  mixins: [playerMixin],
  methods: {
    ...mapActions(['savePlayHistory']),
    ...mapMutations({
      setFullScreen: 'SET_FULL_SCREEN',
      setPlayingState: 'SET_PLAYING_STATE'
    }),
    back () {
      this.setFullScreen(false)
    },
    open () {
      this.setFullScreen(true)
    },
    _getCurrentUrl (mid) {
      if (!mid) {
        return
      }
      getSongUrl(mid)
        .then(result => {
          this.createdTime = Date.now()
          if (result) {
            this.songUrl = result
            this.savePlayHistory(this.currentSong) // 歌曲加载成功，放入播放历史
          } else {
            Toast()
            this.songUrl = ''
            this.$refs.audio.currentTime = 0
            if (this.currentLyric) {
              this.currentLyric.seek(0)
              this.currentLyric.stop()
            }
          }
        })
        .catch(err => {
          console.log(err.message)
        })
    },
    _getLyric () {
      if (!this.currentSong || this.currentIndex === -1) {
        return
      }
      this.playerReady = false
      this.currentLyric = null
      this.currentSong.getLyric().then((lyric) => {
        // 获取歌曲url会比获取歌词快，因此要算时差
        let timeDiff = 0
        if (this.createdTime !== 0) {
          timeDiff = Date.now() - this.createdTime
          timeDiff = timeDiff > 0 ? timeDiff : 0
        }
        this.currentLyric = new Lyric(lyric, this.handleLyric)
        if (this.playing) {
          this.currentLyric.seek(timeDiff)
        }
        this.playerReady = true
      }).catch(() => {
        this.playingLyric = ''
        this.currentLyric = null
        this.currentLineNum = 0
      })
    },

    handleLyric ({ lineNum, txt }) {
      this.currentLineNum = lineNum
      if (lineNum > 5) {
        let lineEl = this.$refs.lyricLine[lineNum - 5]
        this.$refs.lyricList.scrollToElement(lineEl, 1000)
      } else {
        this.$refs.lyricList.scrollTo(0, 0, 1000)
      }
      this.playingLyric = txt
    },

    audioPlay () {
      this.playerReady = true
      if (this.currentLyric) {
        this.currentLyric.seek(this.currentTime * 1000)
      }
    },
    audioPause () {
      if (this.currentLyric) {
        this.currentLyric.togglePlay()
      }
    },

    // 播放相关
    togglePlaying () {
      setTimeout(() => {
        if (!this.songUrl) {
          Toast()
          this.setPlayingState(false)
          return null
        }
        this.setPlayingState(!this.playing)
      }, 200)
    },

    next () {
      this.$nextTick(() => {
        if (this.playerReady) {
          // 歌单长度为1
          if (this.playlist.length === 1) {
            this.loop()
            return
          } else {
            let nextIndex = this.currentIndex + 1
            if (nextIndex === this.playlist.length) {
              nextIndex = 0
            }
            this.setCurrentIndex(nextIndex)
          }
          this.playerReady = false
        }
      })
    },

    prev () {
      this.$nextTick(() => {
        if (this.playerReady) {
          if (this.playlist.length === 1) {
            this.loop()
          } else {
            let prevIndex = this.currentIndex - 1
            if (prevIndex === -1) {
              prevIndex = this.playlist.length - 1
            }
            this.setCurrentIndex(prevIndex)
          }
          if (!this.playing) {
            this.togglePlaying()
          }
          this.playerReady = false
        }
      })
    },

    loop () {
      this.$nextTick(() => {
        if (!this.songUrl) {
          Toast()
          this.setPlayingState(false)
          return null
        }
        if (this.currentLyric) {
          this.currentTime = 0
          this.currentLyric.seek(0)
        }
        this.$refs.audio.currentTime = 0
        this.$refs.audio.play()
        this.setPlayingState(true)
      })
    },

    ended () {
      if (this.mode === playMode.loop) {
        this.loop()
      } else {
        this.next()
      }
    },

    error () {
      // 加载失败， 但是用户依然需要上/下一曲
      this.playerReady = true
    },

    updateTime (e) {
      this.currentTime = e.target.currentTime
    },

    onProgressBarChange (percent) {
      const currentTime = this.currentSong.duration * percent
      this.$refs.audio.currentTime = currentTime
      if (!this.playing) {
        this.setPlayingState(true)
      }
      if (this.currentLyric) {
        this.currentLyric.seek(currentTime * 1000)
      }
    },

    _getPosAndScale () {
      const targetWidth = 40
      const paddingLeft = 40
      const paddingBottom = 30
      const paddingTop = 80
      const width = window.innerWidth * 0.8
      const scale = targetWidth / width
      const x = -(window.innerWidth / 2 - paddingLeft)
      const y = window.innerHeight - paddingTop - width / 2 - paddingBottom
      return { x, y, scale }
    },
    // 钩子动画
    enter (el, done) {
      const { x, y, scale } = this._getPosAndScale()
      let animation = {
        0: {
          transform: `translate3d(${x}px, ${y}px, 0) scale(${scale})`
        },
        60: {
          transform: `translate3d(0,0,0) scale(1.1)`
        },
        100: {
          transform: `translate3d(0,0,0) scale(1)`
        }
      }
      animations.registerAnimation({
        name: 'move',
        animation,
        presets: {
          duration: 400,
          easing: 'linear'
        }
      })
      animations.runAnimation(this.$refs.cdWrapper, 'move', done)
    },
    afterEnter () {
      animations.unregisterAnimation('move')
      this.$refs.cdWrapper.style.animation = ''
    },
    leave (el, done) {
      const { x, y, scale } = this._getPosAndScale()
      this.$refs.cdWrapper.style.transition = 'all .4s'
      this.$refs.cdWrapper.style[transform] = `translate3d(${x}px,${y}px,0) scale(${scale})`
      this.$refs.cdWrapper.addEventListener('transitionend', done)
    },
    afterLeave (el) {
      this.$refs.cdWrapper.style.transition = ''
      this.$refs.cdWrapper.style[transform] = ''
    },

    // touch事件
    middleTouchStart (e) {
      this.touch.initiated = true
      this.touch.moved = false
      const touch = e.touches[0]
      this.touch.startX = touch.pageX
      this.touch.startY = touch.pageY
    },
    middleTouchMove (e) {
      if (!this.touch.initiated) {
        return
      }
      const touch = e.touches[0]
      const deltaX = touch.pageX - this.touch.startX
      const deltaY = touch.pageY - this.touch.startY
      if (Math.abs(deltaX) < Math.abs(deltaY)) {
        return
      }
      if (!this.touch.moved) {
        this.touch.moved = true
      }
      const left = this.currentShow === 'cd' ? 0 : -window.innerWidth // 隐藏的左边内容的距离
      const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
      this.touch.percent = Math.abs(offsetWidth / window.innerWidth)
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
      this.$refs.lyricList.$el.style[transitionDuration] = 0
      this.$refs.middleL.style.opacity = 1 - this.touch.percent
      this.$refs.middleL.style[transitionDuration] = `0`
    },
    middleTouchEnd () {
      if (!this.touch.moved) {
        return null
      }
      let offset = 0
      let opacity = 0
      if (this.currentShow === 'cd') {
        if (this.touch.percent < 0.1) {
          offset = 0
          opacity = 1
        } else {
          offset = -window.innerWidth
          opacity = 0
        }
      } else {
        if (this.touch.percent > 0.1) {
          offset = 0
          opacity = 1
        } else {
          offset = -window.innerWidth
          opacity = 0
        }
      }
      this.currentShow = opacity === 0 ? 'lyric' : 'cd'
      const time = 300 // 动画时长
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offset}px,0,0)`
      this.$refs.lyricList.$el.style[transitionDuration] = `${time}ms`
      this.$refs.middleL.style.opacity = opacity
      this.$refs.middleL.style[transitionDuration] = `${time}`
    },
    showPlaylist () {
      this.$refs.playlist.show()
    }
  },
  watch: {
    currentSong (newVal, oldVal) {
      if (!newVal || newVal.id === oldVal.id) {
        return
      }
      if (this.currentLyric) {
        this.currentLyric.stop()
        this.currentLineNum = 0
        this.playingLyric = ''
      }
      this.currentLyric = null
      this.songUrl = null
      this.$refs.audio.currentTime = 0
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this._getCurrentUrl(newVal.mid)
        this._getLyric()
      }, 500)
    },
    songUrl (newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.$refs.audio.play()
          this.setPlayingState(true)
        })
      } else {
        this.$nextTick(() => {
          this.$refs.audio.currentTime = 0
          this.$refs.audio.pause()
          this.setPlayingState(false)
          if (this.currentLyric) {
            this.currentLyric.stop()
          }
        })
      }
    },
    playing (newVal) {
      const audio = this.$refs.audio
      this.$nextTick(() => {
        if (audio) {
          newVal ? audio.play() : audio.pause()
        }
      })
    },
    fullScreen (newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.$refs.lyricList.refresh()
          if (this.currentLineNum > 5) {
            let lineEl = this.$refs.lyricLine[this.currentLineNum - 5]
            this.$refs.lyricList.scrollToElement(lineEl, 0)
          }
        })
      }
    }
  },
  components: { ProgressBar, ProgressCircle, Scroll, Playlist },
  created () {
    this.touch = {}
  },
  filters: {
    timeFormat: function (data) {
      data = parseInt(data)
      let minute = Math.floor(data / 60)
      minute = minute < 10 ? '0' + minute : minute
      let seconds = data % 60
      seconds = seconds < 10 ? '0' + seconds : seconds
      return minute + ':' + seconds
    }
  }
}
</script>

<style lang="less" scoped>
@import "~common/css/variable";
@import "~common/css/mixin";

.player {
  .normal-player {
    position: fixed;
    left: 0;
    bottom: 0;
    top: 0;
    right: 0;
    z-index: 150;
    background-color: @color-background;

    .background {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      opacity: 0.6;
      filter: blur(20px);
    }

    .top {
      position: relative;
      margin-bottom: 25px;

      .back {
        position: absolute;
        top: 0;
        left: 6px;
        z-index: 50;

        .icon-back {
          display: block;
          padding: 9px;
          font-size: @font-size-large-x;
          color: @color-theme;
          transform: rotate(-90deg);
        }
      }

      .title {
        width: 70%;
        margin: 0 auto;
        line-height: 40px;
        text-align: center;
        .no-wrap;
        font-size: @font-size-large;
        color: @color-text;
      }

      .subtitle {
        line-height: 20px;
        text-align: center;
        font-size: @font-size-medium;
        color: @color-text;
      }
    }

    .middle {
      position: fixed;
      width: 100%;
      top: 80px;
      bottom: 170px;
      white-space: nowrap;
      font-size: 0;

      .middle-l {
        display: inline-block;
        vertical-align: top;
        position: relative;
        width: 100%;
        height: 0;
        padding-top: 80%;

        .cd-wrapper {
          position: absolute;
          left: 10%;
          top: 0;
          width: 80%;
          height: 100%;

          .cd {
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            border: 10px solid rgba(255, 255, 255, 0.1);
            border-radius: 50%;

            &.play {
              animation: rotate 20s linear infinite;
            }

            &.pause {
              animation-play-state: paused;
            }

            .image {
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              border-radius: 50%;
            }
          }
        }

        .playing-lyric-wrapper {
          width: 80%;
          margin: 30px auto 0 auto;
          overflow: hidden;
          text-align: center;

          .playing-lyric {
            height: 20px;
            line-height: 20px;
            font-size: @font-size-medium;
            color: @color-text-l;
          }
        }
      }

      .middle-r {
        display: inline-block;
        vertical-align: top;
        width: 100%;
        height: 100%;
        overflow: hidden;

        .lyric-wrapper {
          width: 80%;
          margin: 0 auto;
          overflow: hidden;
          text-align: center;

          .text {
            line-height: 32px;
            color: @color-text-l;
            font-size: @font-size-medium;
            &.current {
              color: @color-text;
            }
          }
        }
      }
    }

    .bottom {
      position: absolute;
      bottom: 50px;
      width: 100%;

      .dot-wrapper {
        text-align: center;
        font-size: 0;

        .dot {
          display: inline-block;
          vertical-align: middle;
          margin: 0 4px;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: @color-text-l;

          &.active {
            width: 20px;
            border-radius: 5px;
            background-color: @color-text-ll;
          }
        }
      }

      .progress-wrapper {
        display: flex;
        align-items: center;
        width: 80%;
        margin: 0 auto;
        padding: 10px 0;

        .time {
          color: @color-text;
          font-size: @font-size-small;
          flex: 0 0 30px;
          line-height: 30px;
          width: 30px;

          &.time-l {
            text-align: left;
          }

          &.time-r {
            text-align: right;
          }
        }

        .progress-bar-wrapper {
          flex: 1;
          margin: 0 5px;
        }
      }

      .operators {
        display: flex;
        align-items: center;

        .icon {
          flex: 1;
          color: @color-theme;

          &.disable {
            color: @color-theme-d;
          }

          i {
            font-size: 30px;
          }
        }

        .i-left {
          text-align: right;
        }

        .i-center {
          text-align: center;
          padding: 0 20px;
          i {
            font-size: 40px;
          }
        }

        .i-right {
          text-align: left;
        }

        .icon-favorite {
          color: @color-sub-theme;
        }
      }
    }
    &.normal-enter-active,
    &.normal-leave-active {
      transition: all 0.4s ease-in-out;
      .top,
      .bottom {
        transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32);
      }
    }
    &.normal-enter,
    &.normal-leave-to {
      opacity: 0;
      .top {
        transform: translate3d(0, -100px, 0);
      }
      .bottom {
        transform: translate3d(0, 100px, 0);
      }
    }
  }

  .mini-player {
    display: flex;
    align-items: center;
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 180;
    width: 100%;
    height: 60px;
    background-color: @color-highlight-background;

    .icon {
      flex: 0 0 40px;
      width: 40px;
      padding: 0 10px 0 20px;

      img {
        border-radius: 50%;

        &.play {
          animation: rotate 10s linear infinite;
        }

        &.pause {
          animation-play-state: paused;
        }
      }
    }

    .text {
      display: flex;
      flex-direction: column;
      justify-content: center;
      flex: 1;
      line-height: 20px;
      overflow: hidden;

      .name {
        margin-bottom: 2px;
        .no-wrap;
        font-size: @font-size-medium;
        color: @color-text;
      }

      .desc {
        .no-wrap;
        font-size: @font-size-small;
        color: @color-text-d;
      }
    }

    .control {
      flex: 0 0 30px;
      width: 30px;
      padding: 0 10px;

      .icon-play-mini,
      .icon-pause-mini,
      .icon-playlist {
        font-size: 30px;
        color: @color-theme-d;
      }

      .icon-mini {
        font-size: 32px;
        position: absolute;
        left: 0;
        top: 0;
      }
    }

    &.mini-enter-active,
    &.mini-leave-active {
      transition: all 0.4s ease-in-out;
    }
    &.mini-enter,
    &.mini-leave-to {
      opacity: 0;
    }
  }
}

@keyframes rotate {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
